package com.example.listossimage.adtest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.listossimage.type.AdSpaceType;
import com.example.listossimage.util.UUIDUtil;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class fileExchangeTest {
    private static final String aesKey = "440dc5eece394470";

    private static final String path_result = "D:\\work\\Adresult_before.txt";
    private static final String path_result_2 = "D:\\work\\Adresult_over.sql";


    public static final String VIPARA = "440dc5eece394470";   //AES 128位数据块对应偏移量为16位
    //AES：加密方式   CBC：工作模式   PKCS5Padding：填充模式
    private static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";
    private static final String CBC_PKCS5_NoPADDING = "AES/CBC/NoPadding";
    private static final String AES = "AES";
    public static final String CODE_TYPE = "UTF-8";  // 编码方式
    public static final String SIGN_ALGORITHMS = "SHA1PRNG";




    public static void main(String[] args) throws Exception {
        List<String> data_new = readFile01(path_result);
        for (String data : data_new) {
            String[] info = data.split("\\|");
            String parkingCode = info[1];
            JSONObject jsonObject = JSONObject.parseObject(info[3]);
            Boolean next = jsonObject.getBooleanValue("isSuccess");
            if (next) {
                String data_obj = jsonObject.getString("data");
                String json_obj = new String(decrypt(data_obj, aesKey));
                JSONArray bInfo_array = JSONObject.parseArray(json_obj);
                JSONObject bInfo = bInfo_array.getJSONObject(0);
                StringBuilder builder = new StringBuilder();
                String parkNumber = bInfo.getString("parkNumber");
                builder.append(parkNumber).append("|");
                JSONArray ads = bInfo.getJSONArray("adSpaceResults");
                for (int i = 0; i < ads.size(); i++) {
                    JSONObject job = ads.getJSONObject(i);
                    String spaceNumber = job.getString("spaceNumber");
                    builder.append(spaceNumber).append("#");
                    String name = job.getString("name");
                    builder.append(name).append("|");


                    Integer triggerEvent = job.getInteger("triggerEvent");
                    AdSpaceType adSpaceType = AdSpaceType.getAdSpaceTypeByIndex(triggerEvent);
                    // 支付确认页 跳过
                    if (adSpaceType == AdSpaceType.PayConfirmPage) {
                        continue;
                    }
                    String spaceKey = job.getString("accountId");
                    String secret = job.getString("secret");

                    String id = UUIDUtil.newOne();
                    String creat_time = "2022-07-25 18:52:46.894";



                    /**
                     * INSERT INTO "open_api"."t_ad_pull"("id", "create_time", "update_time", "mch_id", "parking_id", "on_off_type",
                     * "ad_no", "ad_name", "secret", "spacenumber", "adspacetype")
                     * VALUES ('P2psf28jcd316762', '2022-07-25 18:52:46.894', '2022-09-06 10:16:49.502', '88547usdb7be4e',
                     * 'P2psf28jcd316762', 'on', 's09604900469164', '支付确认页', '1111', '2222', 'PayConfirmPage');
                     * @param args
                     * @throws Exception
                     */
                    String insertSql = "INSERT INTO \"open_api\".\"t_ad_pull\"(\"id\", \"create_time\", \"update_time\", \"mch_id\", \"parking_id\", \"on_off_type\", \"ad_no\", \"ad_name\", \"secret\", \"spacenumber\", \"adspacetype\") VALUES (";
                    insertSql = insertSql.concat("'").concat(id).concat("','").concat(creat_time).concat("','")
                            .concat(creat_time).concat("',").concat("null").concat(",'").concat(parkingCode)
                            .concat("','").concat("on").concat("','").concat(spaceKey).concat("','")
                            .concat(name).concat("','").concat(secret).concat("','").concat(spaceNumber)
                            .concat("','").concat(adSpaceType.name()).concat("');");
                    System.out.println(insertSql);
                    writeError(path_result_2, insertSql);

                }
//                System.out.println(builder.toString());
//                writeError(path_result_2, info[1], info[2], builder.toString());
            }
        }
    }


    public static List<String> readFile01(String path) throws IOException {
        // 使用一个字符串集合来存储文本中的路径 ，也可用String []数组
        List<String> list = new ArrayList<String>();
        FileInputStream fis = new FileInputStream(path);
        // 防止路径乱码   如果utf-8 乱码  改GBK     eclipse里创建的txt  用UTF-8，在电脑上自己创建的txt  用GBK
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        while ((line = br.readLine()) != null) {
            // 如果 t x t文件里的路径 不包含---字符串       这里是对里面的内容进行一个筛选
            if (line.lastIndexOf("---") < 0) {
                list.add(line);
            }
        }
        br.close();
        isr.close();
        fis.close();
        return list;
    }

    public static byte[] decrypt(String content, String password) throws Exception {
        byte[] decodeBase64 = Base64.decodeBase64(content.getBytes());
        SecretKeySpec key = new SecretKeySpec(password.getBytes(CODE_TYPE),AES);
        Cipher cipher = Cipher.getInstance(CBC_PKCS5_NoPADDING);
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(VIPARA.getBytes(CODE_TYPE)));
        byte[] result = cipher.doFinal(decodeBase64);

        return result;
    }


    public static void writeError(String fileName,String parkingId,String code,String content) {
        try {
            // 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾
            randomFile.seek(fileLength);
            String now = LocalDateTime.now()+"|"+parkingId.trim()+"|"+code+"|";
            randomFile.write(now.getBytes("utf-8"));
            randomFile.write(content.getBytes("utf-8"));
            randomFile.write("\r\n".getBytes());
            randomFile.close();
        } catch (IOException e) {
            return;
//            log.error("将内容写入到txt文件中出现异常：",e);
        }
    }


    public static void writeError(String fileName, String content) {
        try {
            // 打开一个随机访问文件流，按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾
            randomFile.seek(fileLength);
            randomFile.write(content.getBytes("utf-8"));
            randomFile.write("\r\n".getBytes());
            randomFile.close();
        } catch (IOException e) {
            return;
//            log.error("将内容写入到txt文件中出现异常：",e);
        }
    }

}
